package com.example.easytts.controller

import com.example.easytts.model.OcrUsage
import com.example.easytts.model.User
import com.example.easytts.repository.OcrUsageRepository
import com.example.easytts.repository.UserRepository
import com.example.easytts.service.UserService
import jakarta.servlet.http.HttpServletRequest
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile
import org.springframework.web.client.RestTemplate
import org.springframework.http.HttpEntity
import org.springframework.http.HttpHeaders
import org.springframework.http.MediaType
import org.springframework.util.LinkedMultiValueMap
import org.springframework.util.MultiValueMap
import java.io.File
import java.time.LocalDate
import java.time.LocalDateTime
import java.util.*

@RestController
@RequestMapping("/api/upload")
class ImageUploadController @Autowired constructor(
    private val ocrUsageRepository: OcrUsageRepository,
    private val userRepository: UserRepository,
    private val userService: UserService
) {
    @PostMapping("/image")
    fun uploadImage(@RequestParam file: MultipartFile): ResponseEntity<Map<String, Any>> {
        if (file.isEmpty) {
            return ResponseEntity.badRequest().body(mapOf("code" to 400, "message" to "文件不能为空"))
        }
        val ext = file.originalFilename?.substringAfterLast('.', "jpg")?.lowercase() ?: "jpg"
        val filename = UUID.randomUUID().toString() + "." + ext
        val saveDir = File("audio")
        if (!saveDir.exists()) saveDir.mkdirs()
        val saveFile = File(saveDir, filename)
        file.inputStream.use { input ->
            saveFile.outputStream().use { output ->
                input.copyTo(output)
            }
        }
        // 假设静态资源可通过 /audio/ 访问
        val url = "/audio/$filename"
        return ResponseEntity.ok(mapOf(
            "code" to 200,
            "message" to "上传成功",
            "url" to url
        ))
    }

    @PostMapping("/ocr-image")
    fun ocrImage(
        @RequestParam file: MultipartFile,
        request: HttpServletRequest,
        @RequestHeader(value = "Authorization", required = false) authHeader: String?
    ): ResponseEntity<Any> {
        if (file.isEmpty) {
            return ResponseEntity.badRequest().body(mapOf("code" to 400, "message" to "文件不能为空"))
        }
        val today = LocalDate.now()
        var isVip = false
        var userId: Long? = null
        var user: User? = null
        if (!authHeader.isNullOrBlank()) {
            userId = userService.getUserIdFromToken(authHeader)
            if (userId != null) {
                user = userRepository.findById(userId).orElse(null)
                if (user != null) {
                    val vipExpire = user.vipExpire
                    isVip = user.role.equals("vip", true) || (vipExpire != null && vipExpire.isAfter(LocalDateTime.now()))
                }
            }
        }
        if (!isVip) {
            // 非VIP用户或未登录，按userId或IP限制
            val usage = if (userId != null) {
                ocrUsageRepository.findByUserIdAndDate(userId, today)
            } else {
                val ip = request.getHeader("X-Forwarded-For")?.split(",")?.get(0)
                    ?: request.remoteAddr
                ocrUsageRepository.findByIpAndDate(ip, today)
            }
            if (usage != null && usage.count >= 3) {
                return ResponseEntity.status(429).body(mapOf("code" to 429, "message" to "非VIP用户每天只能识别3次，成为VIP可不限次数"))
            }
        }
        // 记录调用
        if (!isVip) {
            if (userId != null) {
                val usage = ocrUsageRepository.findByUserIdAndDate(userId, today)
                if (usage == null) {
                    ocrUsageRepository.save(OcrUsage(userId = userId, date = today, count = 1))
                } else {
                    usage.count += 1
                    ocrUsageRepository.save(usage)
                }
            } else {
                val ip = request.getHeader("X-Forwarded-For")?.split(",")?.get(0)
                    ?: request.remoteAddr
                val usage = ocrUsageRepository.findByIpAndDate(ip, today)
                if (usage == null) {
                    ocrUsageRepository.save(OcrUsage(ip = ip, date = today, count = 1))
                } else {
                    usage.count += 1
                    ocrUsageRepository.save(usage)
                }
            }
        }
        // 调用OCR服务
        val restTemplate = RestTemplate()
        val headers = HttpHeaders()
        headers.contentType = MediaType.MULTIPART_FORM_DATA
        val body: MultiValueMap<String, Any> = LinkedMultiValueMap()
        body.add("file", object : org.springframework.core.io.ByteArrayResource(file.bytes) {
            override fun getFilename(): String? = file.originalFilename ?: "upload.jpg"
        })
        val requestEntity = HttpEntity(body, headers)
        //val ocrServiceUrl = "http://127.0.0.1:5000/api/ocr/azure"
        val ocrServiceUrl = "http://172.17.0.4:5000/api/ocr/azure"
        return try {
            val response = restTemplate.postForEntity(ocrServiceUrl, requestEntity, String::class.java)
            ResponseEntity.status(response.statusCode).body(response.body)
        } catch (e: Exception) {
            ResponseEntity.status(500).body(mapOf("code" to 500, "message" to "识别服务异常: ${e.message}"))
        }
    }
} 